<?php

namespace Core\Application;

use Core\Http\Request;
use Core\Http\Response;

class RunFpm extends Run
{
    /**
     * fpm run
     */
    public function run()
    {
        $method = $_SERVER['REQUEST_METHOD'];
        $uri = $_SERVER['REQUEST_URI'];

        // 初始化请求信息
        $this->initializeRequest();

        // 调度处理
        $this->dispatch($method, $uri);

        // 输出数据到客户端
        $this->responseSend();
    }

    /**
     * 初始化Request
     */
    public function initializeRequest()
    {
        // The GET parameters
        $query = $_GET;

        // The POST parameters
        $request = $_POST;

        // The request attributes (parameters parsed from the PATH_INFO, ...)
        $attributes = [];

        // The COOKIE parameters
        $cookies = $_COOKIE;

        // The FILES parameters
        $files = $_FILES;

        // The SERVER parameters
        $server = $_SERVER;
        if (!array_key_exists('HTTP_X-Request-Id', $server)) {
            $server['HTTP_X-Request-Id'] = substr(md5(uniqid()), 0, 6);
        }

        // The raw body data
        $content = file_get_contents('php://input');

        Request::getInstance()->initialize(
            $query,
            $request,
            $attributes,
            $cookies,
            $files,
            $server,
            $content
        );
    }

    /**
     * 输出返回数据到客户端
     */
    public function responseSend()
    {
        Response::getInstance()->send();
    }
}
